<template>
  <div class="home">
    <h1>商品信息</h1>
    <table border="1" width="800">
      <tr>
        <th>id</th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in $store.state.list" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.count > 0 ? item.count : "" }}</td>
        <td>
          <button v-if="item.count == 0" @click="add(index)">加入购物车</button>
          <div v-else>
            <button @click="add(index)">+</button>
            <button @click="min(index)">-</button>
          </div>
        </td>
      </tr>
    </table>

    <h1>购物车信息 一共有{{ sum }}个商品</h1>

    <button @click="clear">清空购物车</button>
    <table border="1" width="800">
      <tr>
        <th>id</th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
      <tr
        v-for="(item, index) in $store.state.list"
        v-show="item.count > 0"
        :key="item.id"
      >
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.count > 0 ? item.count : "" }}</td>
        <td>
          <button @click="add(index)">+</button>
          <button @click="min(index)">-</button>
          <button @click="del(index)">x</button>
        </td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$axios.get("data.json").then((res) => {
      console.log(res);
      this.$store.commit("setlist", res.data.productsData);
    });
  },
  methods: {
    add(index) {
      this.$store.commit("adds", index);
    },
    min(index) {
      this.$store.commit("min", index);
    },
    del(index) {
      this.$store.commit("del", index);
    },
    clear() {
      this.$store.commit("clear");
    },
  },
  computed: {
    sum() {
      var num = 0;
      this.$store.state.list.forEach((item) => {
        num += item.count;
      });
      return num;
    },
  },
};
</script>
